const axios = require('axios');
const FormData = require('form-data');

async function obationAccessToken(apiUrl, username, password){
    let data = new FormData();
    data.append('username', username);
    data.append('password', password);
    data.append('grant_type', 'password');
    data.append('scope', 'read');

    let config = {
        method: 'post',
        maxBodyLength: Infinity,
        url: apiUrl,
        headers: { 
            'Authorization': 'Basic c3NvLWdhdGV3YXk6c3NvLWdhdGV3YXktc2VjcmV0', 
            'Content-Type': 'application/x-www-form-urlencoded', 
            ...data.getHeaders()
        },
        data : data
    };

    try {
        let response = await axios.request(config);
        return response.data.access_token;
    } catch(error) {
        console.log(error);
        throw error;
    }
}

async function httpPost(apiUrl, body, token) {    
    let config = {
      method: 'post',
      maxBodyLength: Infinity,
      url: apiUrl,
      headers: { 
        'Content-Type': 'application/json', 
        'Authorization': 'Bearer ' + token
      },
      data :  JSON.stringify(body)
    };
    
    try {
        let response = await axios.request(config);
        return response.data;
    } catch(error) {
        console.log(error);
        return null
    }
}

module.exports = {
    obationAccessToken,
    httpPost
};